package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Map;

/**
 * 入住Service业务层处理
 * 
 * @author Jiagege
 * @date 2025-07-23
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private BedMapper bedMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Override
    @Transactional
    public void applyCheckIn(CheckInApplyDto dto) {
        //1.判断老人是否入住
        //若老人已入住，直接返回
        //若老人未入住，走后续流程
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 1));
        if (ObjectUtils.isNotEmpty(elder)) {
//        throw new RuntimeException("老人已入住");
            return;
        }

        //2.更新床位状态为已入住

        //todo selectBedById??selectById
        Bed bed = bedMapper.selectBedById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //3、新增或更新老人信息
        Elder newElder = insertOrUpdateElderInfo(dto, bed);

        //4.新增签约办理信息
        insertContractInfo(dto,newElder);
        //5.新增入住信息
        CheckIn checkIn = insertCheckInInfo(dto, newElder);
        //6.新增入住配置信息
        insertCheckInConfigInfo(dto, checkIn);
    }



    /**
     * 新增或更新老人信息
     *
     * @param dto
     * @param bed
     * @return
     */
    private Elder insertOrUpdateElderInfo(CheckInApplyDto dto, Bed bed) {
        Elder elder = new Elder();
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);//状态（0：禁用，1:启用  2:请假 3:退住中 4入住中 5已退住）
        //todo 插入或更新老人信息
        Elder newElder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, elder.getIdCardNo())
                .ne(Elder::getStatus, 1));
        if (ObjectUtils.isNotEmpty(newElder)) {
            //若不为空，更新老人信息
            elderMapper.updateById(elder);
        }else{
            //若为空，新增老人信息
            elderMapper.insert(elder);
        }
        return elder;


    }

    /**
     * 新增签约办理
     */
    private void insertContractInfo(CheckInApplyDto dto, Elder newElder) {
        Contract contract = new Contract();
        CheckInContractDto contractDto = dto.getCheckInContractDto();
        BeanUtils.copyProperties(contractDto, contract);
        contract.setElderId(Integer.valueOf(newElder.getId()+""));
        contract.setElderName(newElder.getName());
        String contractNumber = "Zz"+CodeGenerator.generateContractNumber();
        contract.setContractNumber(contractNumber);//合同编号
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        contract.setStartDate(startDate);
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        LocalDateTime now = LocalDateTime.now();
        boolean flag = startDate.isBefore(now);
        contract.setStatus(flag?1:0);//状态 (0: 未生效, 1: 已生效, 2: 已过期, 3: 已失效)
        contractMapper.insert(contract);
    }


    /**
     * 新增入住信息
     *
     * @return
     */
    private CheckIn insertCheckInInfo(CheckInApplyDto dto, Elder elder) {
        CheckIn checkIn = new CheckIn();
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        BeanUtils.copyProperties(checkInConfigDto, checkIn);
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());

        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn;

    }


    /**
     * 新增入住配置信息
     */
    private void insertCheckInConfigInfo(CheckInApplyDto dto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        BeanUtils.copyProperties(checkInConfigDto, checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }


    @Override
    public Map<String, Object> getCheckInDetailById(Long id) throws JsonProcessingException {
        Map<String, Object> resultMap = new HashMap<>();

        CheckInElderVo checkInElderVo = checkInConfigMapper.getCheckInElder(id);
        resultMap.put("checkInElderVo",checkInElderVo);

        List<ElderFamilyVo> elderFamilyVoList = getElderFamilyVoList(id);
        resultMap.put("elderFamilyVoList", elderFamilyVoList);

        CheckInConfigVo checkInConfigDto = checkInConfigMapper.getCheckInConfig(id);
        resultMap.put("checkInConfigVo",checkInConfigDto);

        Contract contract = checkInConfigMapper.getContract(id);
        resultMap.put("contract",contract);

        return resultMap;
    }

    private  List<ElderFamilyVo> getElderFamilyVoList(Long id) throws JsonProcessingException {
        String elderFamilyJson = checkInConfigMapper.getElderFamilyInfo(id);
        ObjectMapper objectMapper = new ObjectMapper();
        // 直接转换为 List<ElderFamilyVo>
        List<ElderFamilyVo> elderFamilyVoList = objectMapper.readValue(
                elderFamilyJson, new TypeReference<List<ElderFamilyVo>>() {
                }
        );
        return elderFamilyVoList;
    }


}




























